<?php
include('common/constants.php');
include('common/db.php');

function generateRandomString() {

    $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
    $randomString = '';
    for ($i = 0; $i < 5; $i++) {
        $randomString .= $characters[rand(0, strlen($characters) - 1)];
    }
    return $randomString;
}



if (!isset( $_POST )){
	echo "Nothing to save.";
}

//echo var_dump($_POST);

//create array to temporarily grab variables
$input_arr = array();

//grabs the $_POST variables and adds slashes
foreach ($_POST as $key => $input_arr) {
	$_POST[$key] = addslashes(htmlspecialchars($input_arr));
}

$act_code = generateRandomString();

	$sql = " INSERT INTO `user`(`email`, `password`, `user_type`, `name`, `gender`, `age`, `profession`, `phone_number`, `address`, activation_code)  ";
	$sql .= " VALUES('{$_POST['txt_usrname']}', '{$_POST['txt_pwd']}', '{$_POST['usrTypeRadio']}', '{$_POST['txt_firstname']} {$_POST['txt_lastname']}', '{$_POST['gender']}', '{$_POST['age']}', '{$_POST['prof']}', '{$_POST['txt_mobile']}', '{$_POST['address']}', '" . $act_code . "');";

if(mysql_query($sql)){
	
	$sql2 = "INSERT INTO `user_preference`(`email`, `origin`, `destination`) ";
	$sql2 .= " VALUES('{$_POST['txt_usrname']}', '{$_POST['origin']}', '{$_POST['destination']}');";
	
	if(mysql_query($sql2)){
		//echo "Saving preferences successful";
		echo "success";
	}else{
		//echo "Saving preferences fail";
		echo "fail";
	}

	$message = '';
	$message .= 'Hi ' . $_POST['txt_firstname']	. ", <br />";
	$message .= "Thanks for registering with CarPooling.lk. Your e-mail ". $_POST['txt_usrname']	. " must be confirmed before using it to log in to our website. <br />";
	$message .= "To confirm the e-mail and instantly log in, please, use this confirmation link. This link is valid only once. <br />";
	$message .= "http://carpooling.lk/beta/activate_account.php?activation_code=" . $act_code;

	$to = $_POST['txt_usrname'];
	$subject = "CarPooling.lk - Account confirmation for - " . $_POST['txt_firstname'];
	$headers = "From: " . CONTACT_MAIL_FROM . "\r\n";
	$headers .= 'Cc: ' . CONTACT_MAIL_INTERNAL_CC . "\r\n";
	$headers .= 'Bcc: ' . CONTACT_MAIL_INTERNAL_BCC . "\r\n";
	$headers .= "MIME-Version: 1.0\r\n";
	$headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";
    if (mail($to, $subject, $message, $headers)) {
    	//echo 'Your message has been sent.';
    } else {
    	//echo 'There was a problem sending the email.';
    }

    // DON'T BOTHER CONTINUING TO THE HTML...
    die();

}else{
	echo "fail";
}







